package com.fqdf.framework.android.util;

import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;


import com.fqdf.framework.android.view.LoadMoreListView;
import com.fqdf.framework.android.view.LoadMoreRecycleView;

import org.joda.time.DateTime;

import java.util.List;

/**
 * @author 张枭
 * @version V1.0
 * @date 2017/2/26
 * @desc Android组件工具类
 */
public class AndroidUtils {

    private static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

    private AndroidUtils() {

    }

    /**
     * 隐藏键盘
     *
     * @param context
     */
    public static void hideSoftKeyboard(Activity context) {
        InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), 0);
    }

    /**
     * 获取activity对应的窗口大小尺寸
     *
     * @param mContext 上下文内容
     * @return 尺寸的point对象
     */
    public static Point getWindowsSize(Activity mContext) {
        WindowManager windowManager = mContext.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Point point = new Point();
        display.getSize(point); //设置宽度
        return point;
    }

    /**
     * 隐藏键盘
     *
     * @param context
     * @param paramEditText
     */
    public static void hideSoftInput(Context context, View paramEditText) {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(paramEditText.getWindowToken(), 0);
    }

    /**
     * 获取颜色值
     *
     * @param context
     * @param colorRes
     * @return
     */
    public static int getColor(Context context, int colorRes) {
        int colorValue;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            colorValue = context.getResources().getColor(colorRes, null);
        } else {
            colorValue = context.getResources().getColor(colorRes);
        }
        return colorValue;
    }


    public static void gotoHome(Context context) {
        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);

        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        context.startActivity(mHomeIntent);
    }

    /**
     * 是否是所支持的版本
     */
    public static boolean isSupportVersion(int version) {
        return Build.VERSION.SDK_INT >= version;
    }


    /**
     * 判断微信是否安装
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        return isAppAvilible(context, "com.tencent.mm");
    }

    /**
     * 判断是否安装某个app
     *
     * @param context
     * @param appPackageName
     * @return
     */
    public static boolean isAppAvilible(Context context, String appPackageName) {
        if (TextUtils.isEmpty(appPackageName)) {
            return false;
        }

        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(appPackageName)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取转化的时间
     *
     * @param timeStr
     * @return
     */
    public static String getConvTime(String timeStr) {
        return getConvTime(timeStr, null);
    }

    /**
     * 获取转化的时间
     *
     * @param timeStr
     * @return
     */
    public static String getConvTime(String timeStr, String format) {
        if (TextUtils.isEmpty(timeStr)) {
            return timeStr;
        }
        String time = null;
        try {
            long lTime = Long.valueOf(timeStr);
            time = getConvTime(lTime, format);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return time;
    }

    public static String getConvTime(long time) {
        return getConvTime(time, TIME_FORMAT);
    }

    public static String getConvTime(long time, String format) {

        return new DateTime(time).toString(format == null ? TIME_FORMAT : format);
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getCurData() {
        return getConvTime(System.currentTimeMillis());
    }

    /**
     * 获取程序版本号
     *
     * @return
     */
    public static String getAppVersion(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            return "1.0.0";
        }
    }

    /**
     * 获取drawable 根据资源id
     *
     * @param context 上下文内容
     * @param res     资源文件
     * @return drawable对象
     */
    public static Drawable getDrawableNoTheme(Context context, int res) {
        return getDrawableWithTheme(context, res, null);
    }

    /**
     * 获取drawable 其中drawable为带主题的资源
     *
     * @param context 上下文内容
     * @param res     资源文件
     * @return drawable对象
     */
    public static Drawable getDrawableWithTheme(Context context, int res, Resources.Theme theme) {
        if (AndroidUtils.isSupportVersion(21)) {
            return context.getResources().getDrawable(res, theme);
        } else {
            return context.getResources().getDrawable(res);
        }
    }

    /**
     * 获取color 根据资源id
     *
     * @param context 上下文内容
     * @param res     资源文件
     * @return color
     */
    public static int getColorNoTheme(Context context, int res) {
        return getColorWithTheme(context, res, null);
    }

    /**
     * 获取color 其中drawable为带主题的资源
     *
     * @param context 上下文内容
     * @param res     资源文件
     * @return color
     */
    public static int getColorWithTheme(Context context, int res, Resources.Theme theme) {
        if (AndroidUtils.isSupportVersion(23)) {
            return context.getResources().getColor(res, theme);
        } else {
            return context.getResources().getColor(res);
        }
    }

    /**
     * 处理加载更多状态
     *
     * @param data
     */
    private void handleLoadMoreStatus(LoadMoreListView listView, List<?> data, int limitSize) {
        if (data == null) {
            listView.setCanLoadMore(false);
            return;
        }

        listView.setCanLoadMore(data.size() == limitSize);
    }

    /**
     * 处理加载更多状态
     *
     * @param data
     */
    private void handleLoadMoreStatus(LoadMoreRecycleView recycleView, List<?> data, int limitSize) {
        if (data == null) {
            recycleView.setCanLoadMore(false);
            return;
        }

        recycleView.setCanLoadMore(data.size() == limitSize);
    }

    /**
     * 处理加载更多状态
     *
     * @param data
     */
    private void handleLoadMoreStatus(LoadMoreListView listView, List<?> data) {
        listView.setCanLoadMore(!CheckLogicUtil.isEmpty(data));
    }

    /**
     * 处理加载更多状态
     *
     * @param data
     */
    private void handleLoadMoreStatus(LoadMoreRecycleView recycleView, List<?> data) {
        recycleView.setCanLoadMore(!CheckLogicUtil.isEmpty(data));
    }

    /**
     * 判断是否有处理intent的app
     *
     * @param context 上下文内容
     * @param intent  处理的intent
     * @return true说明有处理intent的app
     */
    public static boolean hasHandleIntentApp(Context context, Intent intent) {
        // 判断是否有activity能接收intent请求
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
        return activities.size() > 0;
    }

    /**
     * 获取发送mail的intent
     *
     * @param email email地址
     * @return Intent内容
     */
    public static Intent getMailIntent(String email) {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:" + email));
        intent.putExtra(Intent.EXTRA_SUBJECT, Constants.BLANK);
        intent.putExtra(Intent.EXTRA_TEXT, Constants.BLANK);
        return intent;
    }

    /**
     * 获取打开电话的intent
     *
     * @param telPhone 电话号码
     * @return intent内容
     */
    public static Intent getTelIntent(String telPhone) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.DIAL");
        intent.setData(Uri.parse("tel:" + telPhone));
        return intent;
    }

    /**
     * 获取拍照intent
     *
     * @param uri 文件存储的uri
     * @return intent内容
     */
    public static Intent getCameraIntent(Uri uri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        return intent;
    }

    /**
     * 选择照片
     */
    public static Intent getPhotoIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        return intent;
    }

    /**
     * 判断是否支持蓝牙
     *
     * @param context 上下文内容
     * @return true代表支持蓝牙，false代表不支持蓝牙
     */
    public static boolean isSupportBluetooth(Context context) {

        BluetoothAdapter adapter = null;
        if (isSupportVersion(18)) {
            final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (bluetoothManager != null) {
                adapter = bluetoothManager.getAdapter();
            }
        } else {
            adapter = BluetoothAdapter.getDefaultAdapter();
        }
        return adapter != null;
    }

    /**
     * 判断是否支持BLE蓝牙设备
     *
     * @param context 上下文内容
     * @return true代表支持BLE蓝牙
     */
    public static boolean isSupportBLE(Context context) {
        return isSupportVersion(18) && isSupportBluetooth(context)
                && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
    }

    public static class MultiClickPreventer {
        private static final long DELAY_IN_MS = 500;

        public static void preventMultiClick(final View view) {
            if (!view.isClickable()) {
                return;
            }
            view.setClickable(false);
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    view.setClickable(true);
                }
            }, DELAY_IN_MS);
        }
    }

    /**
     * 是否有应用市场
     * @param context
     * @return
     */
    public static boolean hasAnyMarketInstalled(Context context) {

        Intent intent = new Intent();

        intent.setData(Uri.parse("market://details?id=android.browser"));

        List list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

        return 0 != list.size();

    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static boolean isGpsOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
//        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//        if (gps || network) {
//            return true;
//        }

        return gps;
    }
    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }
}
